<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="用户ID" prop="userid">
        <el-input
          v-model="queryParams.userid"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="变动类型" prop="changeType">
        <el-select v-model="queryParams.changeType" placeholder="请选择类型" clearable>
          <el-option label="签到" :value="1" />
          <el-option label="消费" :value="2" />
          <el-option label="充值" :value="3" />
          <el-option label="活动奖励" :value="4" />
          <el-option label="系统赠送" :value="5" />
          <el-option label="退款" :value="6" />
          <el-option label="管理员调整" :value="7" />
          <el-option label="其他" :value="8" />
        </el-select>
      </el-form-item>
      <el-form-item label="记录状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="有效" value="有效" />
          <el-option label="无效" value="无效" />
          <el-option label="已撤销" value="已撤销" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker clearable
          v-model="queryParams.createdAt"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:userPointsLog:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:userPointsLog:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:userPointsLog:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:userPointsLog:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="userPointsLogList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="日志ID" align="center" prop="id" width="80" />
      <el-table-column label="用户ID" align="center" prop="userid" width="100" />
      <el-table-column label="积分变动" align="center" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.pointsChange > 0" style="color: #67c23a; font-weight: bold;">+{{ scope.row.pointsChange }}</span>
          <span v-else style="color: #f56c6c; font-weight: bold;">{{ scope.row.pointsChange }}</span>
        </template>
      </el-table-column>
      <el-table-column label="变动前/后" align="center" width="120">
        <template slot-scope="scope">
          <div>
            <div style="font-size: 12px; color: #909399;">{{ scope.row.pointsBefore }}</div>
            <div style="font-size: 12px; color: #606266;">→ {{ scope.row.pointsAfter }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="变动类型" align="center" prop="changeType" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.changeType === 1" type="success" size="small">签到</el-tag>
          <el-tag v-else-if="scope.row.changeType === 2" type="warning" size="small">消费</el-tag>
          <el-tag v-else-if="scope.row.changeType === 3" type="primary" size="small">充值</el-tag>
          <el-tag v-else-if="scope.row.changeType === 4" type="danger" size="small">活动奖励</el-tag>
          <el-tag v-else-if="scope.row.changeType === 5" type="success" size="small">系统赠送</el-tag>
          <el-tag v-else-if="scope.row.changeType === 6" type="info" size="small">退款</el-tag>
          <el-tag v-else-if="scope.row.changeType === 7" type="warning" size="small">管理员调整</el-tag>
          <el-tag v-else-if="scope.row.changeType === 8" type="info" size="small">其他</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="变动原因" align="center" prop="changeReason" min-width="200" show-overflow-tooltip />
      <el-table-column label="关联业务ID" align="center" prop="relatedId" width="120" show-overflow-tooltip />
      <el-table-column label="操作员" align="center" prop="operator" width="100" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === '有效'" type="success" size="small">有效</el-tag>
          <el-tag v-else-if="scope.row.status === '无效'" type="info" size="small">无效</el-tag>
          <el-tag v-else-if="scope.row.status === '已撤销'" type="danger" size="small">已撤销</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:userPointsLog:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:userPointsLog:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改积分日志对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户ID" prop="userid">
                  <el-input v-model="form.userid" placeholder="请输入用户ID" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="变动类型" prop="changeType">
                  <el-select v-model="form.changeType" placeholder="请选择类型" style="width: 100%">
                    <el-option label="签到" :value="1" />
                    <el-option label="消费" :value="2" />
                    <el-option label="充值" :value="3" />
                    <el-option label="活动奖励" :value="4" />
                    <el-option label="系统赠送" :value="5" />
                    <el-option label="退款" :value="6" />
                    <el-option label="管理员调整" :value="7" />
                    <el-option label="其他" :value="8" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="积分变动值" prop="pointsChange">
                  <el-input-number v-model="form.pointsChange" style="width: 100%" />
                  <span class="form-tip">* 正数为增加，负数为减少</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="变动前积分" prop="pointsBefore">
                  <el-input-number v-model="form.pointsBefore" :min="0" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="变动后积分" prop="pointsAfter">
                  <el-input-number v-model="form.pointsAfter" :min="0" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="记录状态" prop="status">
                  <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                    <el-option label="有效" value="有效" />
                    <el-option label="无效" value="无效" />
                    <el-option label="已撤销" value="已撤销" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="变动原因" prop="changeReason">
                  <el-input v-model="form.changeReason" placeholder="请输入变动原因说明" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="关联业务ID" prop="relatedId">
                  <el-input v-model="form.relatedId" placeholder="如订单号、活动ID等" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="操作员" prop="operator">
                  <el-input v-model="form.operator" placeholder="请输入操作员" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注信息" prop="remark">
                  <el-input 
                    v-model="form.remark" 
                    type="textarea"
                    :rows="3"
                    placeholder="请输入备注信息"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 扩展信息 -->
          <el-tab-pane label="扩展信息" name="extra">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="扩展数据" prop="extraData">
                  <el-input 
                    v-model="form.extraData" 
                    type="textarea"
                    :rows="8"
                    placeholder='请输入JSON格式的扩展数据'
                  />
                  <span class="form-tip">* 请输入合法的JSON格式数据</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUserPointsLog, getUserPointsLog, delUserPointsLog, addUserPointsLog, updateUserPointsLog } from "@/api/system/userPointsLog";

export default {
  name: "UserPointsLog",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      userPointsLogList: [],
      title: "",
      open: false,
      activeTab: 'basic',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userid: null,
        pointsChange: null,
        pointsBefore: null,
        pointsAfter: null,
        changeType: null,
        changeReason: null,
        relatedId: null,
        operator: null,
        remark: null,
        status: null,
        extraData: null,
        createdAt: null,
        updatedAt: null
      },
      form: {},
      rules: {
        userid: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        pointsChange: [
          { required: true, message: "积分变动值不能为空", trigger: "blur" }
        ],
        pointsBefore: [
          { required: true, message: "变动前积分余额不能为空", trigger: "blur" }
        ],
        pointsAfter: [
          { required: true, message: "变动后积分余额不能为空", trigger: "blur" }
        ],
        changeType: [
          { required: true, message: "变动类型不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      listUserPointsLog(this.queryParams).then(response => {
        this.userPointsLogList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        userid: null,
        pointsChange: 0,
        pointsBefore: 0,
        pointsAfter: 0,
        changeType: null,
        changeReason: null,
        relatedId: null,
        operator: null,
        remark: null,
        status: '有效',
        extraData: null,
        createdAt: null,
        updatedAt: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset();
      this.activeTab = 'basic';
      this.open = true;
      this.title = "添加积分日志";
    },
    handleUpdate(row) {
      this.reset();
      this.activeTab = 'basic';
      const id = row.id || this.ids
      getUserPointsLog(id).then(response => {
        this.form = response.data;
        
        // 处理JSON字段
        if (this.form.extraData && typeof this.form.extraData === 'object') {
          this.form.extraData = JSON.stringify(this.form.extraData, null, 2);
        }
        
        this.open = true;
        this.title = "修改积分日志";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const submitForm = JSON.parse(JSON.stringify(this.form));
          
          // 处理JSON字段
          if (submitForm.extraData && typeof submitForm.extraData === 'string') {
            try {
              submitForm.extraData = submitForm.extraData.trim() 
                ? JSON.parse(submitForm.extraData) 
                : null;
            } catch (e) {
              this.$modal.msgError("扩展数据JSON格式不正确");
              return;
            }
          }
          
          if (submitForm.id != null) {
            updateUserPointsLog(submitForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUserPointsLog(submitForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除积分日志编号为"' + ids + '"的数据项？').then(function() {
        return delUserPointsLog(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('system/userPointsLog/export', {
        ...this.queryParams
      }, `userPointsLog_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 4px;
  display: block;
}

::v-deep .el-tabs--border-card {
  box-shadow: none;
}

::v-deep .el-tabs__content {
  padding: 20px;
}
</style>
